package com.basic.common.exception.handle;


import com.basic.common.json.JsonDsUtil;
import com.basic.common.result.WebResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 捕捉异常信息并处理
 * @author
 * @version v_1.0.1
 * @since
 */
public class BaseGlobalDsExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseGlobalDsExceptionHandler.class);

    protected ModelAndView handleError(HttpServletRequest req, HttpServletResponse rsp, Exception e, String errorName, HttpStatus status) throws Exception {
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        WebResult exceptionMsg = ExceptionDsUtil.getExceptionMsg(req, e);
        if (StringUtils.isNotBlank(errorName) && !isAjax(req)) {
            return handleViewError(req.getRequestURL().toString(), exceptionMsg, errorName);
        }
        return handleAjaxError(rsp, JsonDsUtil.beanToJSONStr(exceptionMsg), status);
    }

    protected ModelAndView handleViewError(String url, WebResult exceptionMsg, String viewName) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("url", url);
        String v = "redirect:";
        if (viewName.indexOf(v) < 0){
            mav.addObject("code", exceptionMsg.getCode());
            mav.addObject("exception", exceptionMsg.getException());
            mav.addObject("msg", exceptionMsg.getMsg());
            mav.addObject("timestamp", exceptionMsg.getTimestamp());
        }
        mav.setViewName(viewName);
        return mav;
    }

    protected ModelAndView handleAjaxError(HttpServletResponse rsp, String errorMessage, HttpStatus status) throws IOException {
        rsp.setCharacterEncoding("UTF-8");
        rsp.setStatus(status.value());
        rsp.setContentType("application/json; charset=utf-8");
        PrintWriter writer = rsp.getWriter();
        writer.write(errorMessage);
        writer.flush();
        writer.close();
        return null;
    }

    boolean isAjax(HttpServletRequest request) {
        return ((request.getHeader("accept") != null
                && request.getHeader("accept").contains("application/json"))
                || (request.getHeader("content-type") != null
                && request.getHeader("content-type").contains("application/json"))
                || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").contains("XMLHttpRequest")));
    }

}
